package com.xm.linxiaogang.base.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.text.TextUtils
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import cn.pedant.SweetAlert.SweetAlertDialog
import com.example.baselibrary.R
import com.xm.linxiaogang.base.activity.swipeback.SwipeBackActivity
import io.reactivex.functions.Action

/**
 * 该基类的作用：
 * 1.支持权限申请和处理
 */
open class PermissionActivity : SwipeBackActivity() {
    //权限请求成功时的回调
    private var permissionSuccessAcion: Action? = null

    //权限说明
    private var permissionDescription: String? = null

    //需要申请的权限列表
    private val needPermissions = ArrayList<String>()

    companion object {
        private const val MY_PERMISSIONS_REQUEST = 1001
        private const val PACKAGE_URL_SCHEME = "package:"
        private const val REQUEST_CODE_REQUEST_SETTING = 1027
    }

    /**
     * 请求权限
     *
     * @param permissions               权限列表
     * @param action                    获得权限成功之后的回调
     * @param needPermissionDescription 需要这些权限的说明（当用户拒绝之后，会提示这个说明）
     */
    fun requestPermission(
        permissions: Array<String>,
        action: Action,
        needPermissionDescription: String?
    ) {
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                needPermissions!!.add(permission)
            }
        }
        if (needPermissions == null || needPermissions.size <= 0) { //已经获得权限，直接执行
            try {
                action.run()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return
        }
        var needRationale = false //是否需要权限的原因。当申请的权限被用户拒绝之后，再次申请时会提示
        for (p in needPermissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                needRationale = true
                break
            }
        }
        permissionSuccessAcion = action //获得权限之后的回调
        permissionDescription = needPermissionDescription //申请权限的描述信息
        if (needRationale) { //提示之后再申请权限
            SweetAlertDialog(this)
                .setTitleText(getString(R.string.apply_permission))
                .setContentText(needPermissionDescription)
                .setConfirmClickListener { dialog ->
                    ActivityCompat.requestPermissions(
                        this,
                        needPermissions.toTypedArray(),
                        MY_PERMISSIONS_REQUEST
                    )
                    dialog.dismissWithAnimation()
                }.show()
        } else { //直接申请权限
            ActivityCompat.requestPermissions(
                this,
                needPermissions.toTypedArray(),
                MY_PERMISSIONS_REQUEST
            )
        }
    }

    /**
     * 请求权限之后的回调处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        try {
            if (requestCode == MY_PERMISSIONS_REQUEST) {
                var allGranted = true
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allGranted = false
                    }
                }
                if (allGranted) { //已获得全部权限
                    if (permissionSuccessAcion != null) permissionSuccessAcion!!.run()
                } else { //未获得权限，提示是否打开设置页面
                    if (!TextUtils.isEmpty(permissionDescription)) {
                        SweetAlertDialog(this)
                            .setTitleText(getString(R.string.apply_permission_failure))
                            .setContentText(getString(R.string.goto_setting, permissionDescription))
                            .setCancelText(getString(R.string.cancel))
                            .setConfirmText(getString(R.string.confirm))
                            .setConfirmClickListener { dialog ->
                                startAppSettings(this)
                                dialog.dismissWithAnimation()
                            }
                            .setCancelClickListener { dialog ->
                                dialog.dismissWithAnimation()
                                this.finish()
                            }.show()
                    }
                }
                return
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 返回该页面时的回调处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            if (requestCode == REQUEST_CODE_REQUEST_SETTING) {
                val list: MutableList<String> = ArrayList()
                for (permission in needPermissions!!) {
                    if (ContextCompat.checkSelfPermission(
                            this,
                            permission
                        ) == PackageManager.PERMISSION_DENIED
                    ) {
                        list.add(permission)
                    }
                }
                if (list.size > 0) {
                    if (!TextUtils.isEmpty(permissionDescription)) {
                        SweetAlertDialog(this)
                            .setTitleText(getString(R.string.apply_permission_failure))
                            .setContentText(getString(R.string.goto_setting, permissionDescription))
                            .setCancelText(getString(R.string.cancel))
                            .setConfirmText(getString(R.string.confirm))
                            .setConfirmClickListener { dialog ->
                                startAppSettings(this)
                                dialog.dismissWithAnimation()
                            }
                            .setCancelClickListener { dialog ->
                                dialog.dismissWithAnimation()
                                this.finish()
                            }.show()
                    }
                } else {
                    if (permissionSuccessAcion != null) permissionSuccessAcion!!.run()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 跳转到app的设置页面去设置权限
     */
    private fun startAppSettings(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.parse(PACKAGE_URL_SCHEME + activity.packageName)
        activity.startActivityForResult(intent, REQUEST_CODE_REQUEST_SETTING)
    }
}